var express = require("express");
var router = express.Router();
var { user } = require("../../databases/date");
const jwt = require("jsonwebtoken");
var multiparty = require("multiparty");
const ACCESS_SECRET = "aaa";
const REFRESH_SECRET = "bbb";
/* GET users listing. */
// 中间件
function mid(req,res,next){
  const authheader=req.headers.autherization
  if(!authheader||!authheader.startsWith('Bearer ')){
    return res.status(401).json({err:'Missing token'})
  }
  const accesstoken=authheader.slice(7)
  try{
    const decoded=jwt.verify(accesstoken,ACCESS_SECRET,)
    req.username=decoded.username
    next()

  }catch(err){
    return res.status(401).json({error:'accesstoken过期或者无效'})
  }
}

router.post('/refresh',async(req,res)=>{
  const refreshtoken=req.cookies.refreshtoken
  if(!refreshtoken){
    return res.status(401).json({error:'refreshtoken无'})
  }
  try{
    const decoded=jwt.verify(refreshtoken,REFRESH_SECRET)
    const accesstoken=jwt.sign({username:decoded.username},ACCESS_SECRET,{expiresIn:'15m'})
    res.send({
      data:{
        code:200,
        msg:'刷新成功',
        accesstoken
      }
    })
  }catch(err){
    return res.status(401).json({error:'token无效过期'})
  }
})

// router.get('/ceshi',mid,(req,res)=>{
//   console.log(123);
//   res.status(401)
// })
router.post("/login", async function (req, res, next) {
  let { username, password } = req.body;
  let info = await user.find({ username: username, password: password });
  if (info.length > 0) {
    const accesstoken=jwt.sign(
      {username},
      ACCESS_SECRET,
      {expiresIn:'15m'}
    )
    const refreshtoken=jwt.sign(
      {username},
      REFRESH_SECRET,
      {expiresIn:'7d'}
    )
    res.cookie('refreshtoken',refreshtoken,{
      httpOnly:true,
      secure:false,
      sameSite:'Strict',
      maxAge:7*24*60*60*1000
    })
    res.send({
      data: {
        code: 200,
        msg: "登录成功",
        userId: info[0]._id,
        username: info[0].username,
        accesstoken
      },
    });
  } else {
    res.send({
      data: { code: 500, msg: "用户名或者密码错误" },
    });
  }
  // res.send('respond with a resource');
});
router.post("/register", async (req, res) => {
  // let {username,password,phone}=req.body
  try {
    let info = await user.find({ username: req.body.username });
    if (info.length) {
      res.send({
        data: {
          code: 400,
          msg: "用户名已存在",
        },
      });
    } else {
      await user.insertOne(req.body);
      res.send({
        data: {
          code: 200,
          msg: "注册成功",
        },
      });
    }
  } catch (err) {
    console.log(err);
  }
});
router.get("/info",async (req, res) => {

  let { username } = req.query;
  let info = await user.find({ username: username });
  if (info.length > 0) {
    console.log(info[0]);

    res.send({
      data: {
        code: 200,
        msg: "查询成功",
        phone: info[0].phone,
      },
    });
  } else {
    res.send({
      data: {
        code: 500,
        msg: "查询失败",
      },
    });
  }
});
router.post("/chgmima", async (req, res) => {

  try {
    const { username, password } = req.body;
    console.log(req.body);

    await user.updateOne(
      { username: username },
      { $set: { password: password } }
    );
    res.send({
      data: {
        code: 200,
        msg: "密码修改成功",
        username: username,
      },
    });
  } catch (err) {
    console.log(err);
  }
});
// function parseMuiparty
router.post("/upload", async (req, res) => {
  let form = new multiparty.Form();
  form.uploadDir = "./upload";
  form.parse(req, (err, fields, files) => {
    if (err) {
      console.log(err);
    }
    console.log(files, 222);

    let path = "http://localhost:3000/" + files.img[0].path.replace(/\\/g, "/");

    console.log(path);
    res.send({
      data: {
        code: 200,
        msg: "上传成功",
        path: path,
      },
    });
  });
});

router.post("/chguser", async (req, res) => {
  try {
    const { username, name, sex, birth, img } = req.body;
    await user.findOneAndUpdate(
      { username: username },
      { $set: { name: name, sex: sex, birth: birth, img: img } }
    );
    res.send({
      data: {
        code: 200,
        msg: "信息添加成功",
      },
    });
  } catch (err) {
    console.log(err);
  }
});

router.post("/chguser2", async (req, res) => {
  try {
    const { zfpwd, username } = req.body;
    await user.findOneAndUpdate(
      { username: username },
      { $set: { zfpwd: zfpwd } }
    );
    res.send({
      data: {
        code: 200,
        msg: "信息添加成功",
      },
    });
  } catch (err) {
    console.log(err);
  }
});

module.exports = router;
